import path from 'path';
import fsPromise from 'fs-promise';
import colors from 'colors-console';
import sleep from '../lib/sleep';

let configInit = false;

const defaultConfig = {
    'version': 'v2.4',
    'clientServerPort': 3000,
    'manageServerPort': 3001,
    'clientCORS': true,
    'wwwPath': 'www',
    'prefixHTTPList': [],
    'Cesium': {
        'version': '1.105.2',
        'IonAccessToken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhYzVkMTc1ZS00NTRhLTRjY2QtYTQwZS01YmU2Mjg1ODAwN2YiLCJpZCI6MjU5LCJpYXQiOjE2ODgzOTgwMjl9.MZC_HUBRd0y5HJeB-F5QSpT-fEgTM6mI5gMaSND9FHc'
    },
    'MapBox': {
        'access_token': 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXFhYTA2bTMyeW44ZG0ybXBkMHkifQ.gUGbDOPUN1v1fTs5SeOR4A',
        'header': {
            'Referer': 'https://geojson.io/'
        }
    },
    'CacheSave': {
        'state': true,
        // 缓存到文件
        'CacheSaveFile': true,
        // 缓存到数据库
        'CacheSaveDB': false
    },
    // v2.4版 试用令牌 2023-05-25 ~ 2024-05-25
    'WinUIAuth': '8dda2554f16a103bac984e0f82c0626ff3abef21f8900a8789bc102d292a29c7dcfcf9401797cff20b2b8dec8c42601d07615bb6f7d465fc4347448b1a85d9bcb1bf5e52d2ed6994d607b3c33b2a898f7ed9f3a956a357a797f2101c6a68aa5e78b985f7d3939653e4d5ac9a2d81c325b1819a6d5de37460ef2d73bd05a335251d2a71b5dfa3eabe2e89fd1dbb15dba0cd85dbc6a88389499c4cbfac81a3973dc248e75eb9110e87f22ca1ed13264471473d34a9624073f18202d339a1240a01bae8e969df7046f78b3b35c0c3f058564b0459b42a3253feba175eef0730234df203466e40744dc55887eba31bda7e6c57a1498837421fd04d1a8545c16c6c3a6a741137f4a03c075b9f5cb15846e10b3133cbf9b702a3a2d0582c5fc413cbbb51f908d51fa8e127eecb1841ecf2c8aa24786c96227bf5112d58c849cba3d2958014bebff898741eb8fa7d5a8b2abf1ffb8608c94aa6f605d3be0a8a9f07e3da796bf5295d84043073e7befe76d5088f5986ee15256f01fec54f991e1c20c684dd6373e028ae2bf47dfac818ea51d6c6ca752679522a98ed391691d1c070572974c7619d4d40e06ec5d5b9260e5d6b38c19586924eb61a3d0ae464408635566efd00275f36bcb43cd29aacafd9d427dd5f62aa2eeaad7938c23d5470617316b1e1e052ff94c79811622d2a492f2f84f5fb46f8ced55228a30fdf7c1ce8f99ac1'
};

const configTool = {
    appBasePath: '',
    wwwPath: '',
    config: {} as any,
    async editConfig(key: string, value: any) {
        await this.init();
        let result = false;
        if (typeof this.config[key] === typeof value) {
            this.config[key] = value;
            await fsPromise.writeJSON(path.join(this.appBasePath, '/conf/config.json'), this.config);
            result = true;
        }
        return result;
    },
    async init() {
        return new Promise(async (resolve, reject) => {
            if (!configInit) {
                configInit = true;

                // 是否处于开发环境
                let isDev = !__dirname.includes('snapshot');

                if (isDev) {
                    this.appBasePath = path.join(__dirname, '../../');
                } else {
                    this.appBasePath = path.dirname(process.execPath);
                }

                await fsPromise.ensureDir(path.join(this.appBasePath, '/conf'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileOut'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileDB'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/logs/http'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/www'));

                let configFile = path.join(this.appBasePath, '/conf/config.json');

                // 判断是读取配置文件
                await fsPromise.readJson(configFile).then((d: any) => {
                    if (d.version === defaultConfig.version) {
                        this.config = d;
                    } else {
                        console.log(colors('red', '----|||配置文件版本过低，重置配置文件|||----'));
                        throw new Error('配置文件版本不匹配');
                    }
                }).catch(() => {
                    // 新生成一份配置文件
                    this.config = defaultConfig;
                    fsPromise.writeJSON(configFile, this.config);
                });

                // 判断wwwPath是否是绝对路径
                if (path.isAbsolute(this.config.wwwPath)) {
                    this.wwwPath = path.join(this.config.wwwPath);
                    console.log(this.wwwPath);
                } else {
                    this.wwwPath = path.join(this.appBasePath, this.config.wwwPath);
                }
            }

            while (!configInit) {
                await sleep(50);
            }
            resolve(true);
        });

    },
    preservableONDB() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveDB;
    },
    preservableONFile() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveFile;
    }
};


export default configTool;
